//二叉树的直径
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    int ret;

public:
    int diameterOfBinaryTree(TreeNode* root) {
        ret = 1;
        dfs(root);
        return ret - 1;
    }
    int dfs(TreeNode* root) {
        if (!root)
            return 0;
        int left = dfs(root->left);
        int right = dfs(root->right);
        ret = max(ret, left + right + 1);
        return max(left, right) + 1;
    }
};

//将有序数组转换为二叉搜索树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return bst(nums, 0, nums.size() - 1);
    }
    TreeNode* bst(vector<int>& nums, int left, int right) {
        if (left > right)
            return nullptr;
        int mid = left + (right - left) / 2;
        TreeNode* t = new TreeNode(nums[mid]);
        t->left = bst(nums, left, mid - 1);
        t->right = bst(nums, mid + 1, right);
        return t;
    }
};